﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Http.Formatting;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
using System.Net.Http;
using System.IO;
using System.Net;
using System.Web.Script.Serialization;

namespace PServiceBus.WebAPI {
    public class JavaScriptSerializerFormatter : MediaTypeFormatter {

        public override bool CanWriteType(Type type) {
            if (type == typeof(JValue) || type == typeof(JObject) || type == typeof(JArray))
                return false;

            return true;
        }

        public override bool CanReadType(Type type) {
            return true;
        }

        private static JavaScriptSerializer _serializer = new JavaScriptSerializer();
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger) {
            return Task<object>.Factory.StartNew(() =>
            {
                string json;

                using (var sr = new StreamReader(readStream)) {
                    json = sr.ReadToEnd();
                    sr.Close();
                }

                return _serializer.Deserialize(json, type);
            });
        }

        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext) {
            return Task.Factory.StartNew(() =>
            {
                var json = _serializer.Serialize(value);

                var buffer = System.Text.Encoding.Default.GetBytes(json);
                writeStream.Write(buffer, 0, buffer.Length);
                writeStream.Flush();
            });
        }
    }
}
